package com.mxpio.erp.common.common.provider;

import com.mxpio.erp.common.inventory.entity.Warehouse;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criterion;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.SimpleCriterion;
import com.mxpioframework.security.access.datascope.provider.DataScapeProvider;
import com.mxpioframework.security.entity.Dept;
import com.mxpioframework.security.entity.UserDept;
import com.mxpioframework.security.service.DeptService;
import com.mxpioframework.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author : wpp
 * @Datetime : 2023/4/19 14:25
 * @Desc :
 * @Modor :  Modifytime:
 * @modDesc : 通用 创建人部门及子部门
 */
@Component
public class CreateDeptWithSubProvider implements DataScapeProvider {
    @Autowired
    private DeptService deptService;
    @Override
    @Transactional(readOnly = true)
    public List<Criterion> provide() {
        String loginUsername = SecurityUtils.getLoginUsername();//拿用户所属的部门和仓库信息中的所属部门来匹配
        List<Criterion> appendCriterions = new ArrayList<>();
        if (StringUtils.isBlank(loginUsername)){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));//如果未匹配到过滤条件，则增加一个不能正常匹配到数据的条件
            return appendCriterions;
        }
        Set<String> deptCodeSet = SecurityUtils.getDeptCode();//用户所属部门列表，目前系统不支持多部门
        if (deptCodeSet.isEmpty()){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));
            return appendCriterions;
        }
        Dept deptWithSub = deptService.getDeptWithBranchByCode(deptCodeSet.iterator().next());
        List<String> deptCodes = new ArrayList<>();
        if (deptWithSub==null){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));
            return appendCriterions;
        }
        getDeptCode(deptWithSub,deptCodes);
        appendCriterions.add(new SimpleCriterion("createDept", Operator.IN, deptCodes));
        return appendCriterions;
    }
    private void getDeptCode(Dept dept,List<String> deptCodes){
        deptCodes.add(dept.getDeptCode());
        if (dept.getChildren()!=null&&dept.getChildren().size()>0){
            for (Dept per:dept.getChildren()){
                getDeptCode(per,deptCodes);
            }
        }
    }
}
